module Videre
  class Contacts 
    def initialize
      @items=Hash.new 
    end
 
    def update_item(presence)
      stripped_jid=presence.from.strip.to_s
      resource=presence.from.resource

      # check if we have this JID in memory already, if not, create it
      unless @items[stripped_jid]
        @items[stripped_jid]=Hash.new
      end

     # Check if this JID with this resource is new.
     unless @items[stripped_jid][resource] 
       @items[stripped_jid][resource]=Hash.new # create it
     end

     #
     # Now we are sure we know this fellow, update it's record
     #

     # If offline, delete it
     if presence.type === :unavailable
      @items[stripped_jid].delete(resource)
      return true
     end

     # ok, still here
     @items[stripped_jid][resource]['show']=presence.show
     @items[stripped_jid][resource]['status']=presence.status

    end

    def is_online?(jid, resource)
      if @items[jid]
         return true if @items[jid][resource]
      else
         nil
      end
    end
    
    def find_program(progname, jid=$config['xmpp']['jid'])
     online=Array.new
     if @items[jid]
       @items[jid].each do | resource, info |
         if /^videre_#{progname}_/.match resource
           online.push("#{jid}/#{resource}") unless self.is_busy?(jid, resource)
         end
       end
     end
     return online
    end

    def is_busy?(jid, resource)
       if @items[jid]
         if @items[jid][resource]
            return true if @items[jid][resource]['show']== :dnd
         end
       end
    end

  end
end
